﻿function LoginFactory($http, $q) {

    var Login = function (user) {
        var deferred = $q.defer();
        $http({
            url: '/Token',
            method: 'POST',
            contentType: 'application/x-wwww-form-urlencoded',
            data: "username=" + user.username + "&password=" + user.password + "&grant_type=password"
        }).success(function (data) {
            localStorage.setItem('token', data.access_token);
            deferred.resolve();
        }).error(function (data) {
            localStorage.removeItem('token');
            deferred.reject();
        });
        return deferred.promise;
    }

    var Logout = function () {
        localStorage.removeItem('token');
    }

    var Register = function (user) {
        var deferred = $q.defer();
        $http({
            url: '/api/apiUser',
            method: 'POST',
            data: user
        }).success(function (data) {
            deferred.resolve();
        }).error(function (data) {
            deferred.reject();
        });
        return deferred.promise;
    }

    return {
        Login: Login,
        Logout: Logout,
        Register: Register
    }
}
LoginFactory.$inject = ['$http', '$q'];